/**
 * 
 */
package com.otrace.actions;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.otrace.forms.InstanceCountForm;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.VirtualMachine;

/**
 * @author Prabhu KVN
 * 
 */
public class InstanceCountAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		long startTime = System.currentTimeMillis();
		System.out.println("Start - execute method in:"+this.getClass().getName());
		InstanceCountForm instanceCountForm = (InstanceCountForm) form;
		HttpSession session = request.getSession(false);
		String clazz = instanceCountForm.getClassName();
		long instanceCount = 0;
		if (clazz != null && !clazz.isEmpty()) {
			VirtualMachine virtualMachine = (VirtualMachine) session
					.getValue("JVM");
			if (virtualMachine != null) {
				if (virtualMachine.canGetInstanceInfo()) {
					List<ReferenceType> refTypes = virtualMachine
							.classesByName(clazz);
					
					long count[] = virtualMachine.instanceCounts(refTypes);
					for (long l : count) {
						instanceCount = instanceCount + l;
					}
				} else {
					instanceCount = -1;
				}
			}
		}
		if (-1 == instanceCount) {
			request.setAttribute("instanceCount", "JVM won't support");
		} else {
			request.setAttribute("instanceCount", instanceCount);
		}
		long endTime = System.currentTimeMillis();
		System.out.println("Finish execute method: total time - "+(endTime-startTime));
		return mapping.findForward("success");
	}

}
